package com.daoshu.mds.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.mds.constants.MessageType;
import com.daoshu.mds.constants.MicroGroupType;
import com.daoshu.mds.dispatch.bo.MicroGroupBO;
import com.daoshu.mds.dispatch.entity.MicroGroupBusiness;
import com.daoshu.mds.dispatch.entity.MicroGroupEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMemberEntity;
import com.daoshu.mds.dispatch.entity.MicroGroupMessageEntity;
import com.daoshu.mds.dispatch.qo.MicroGroupQO;
import com.daoshu.mds.message.mapper.MicroGroupMapper;
import com.daoshu.mds.message.mapper.MicroGroupMemberMapper;
import com.daoshu.mds.message.service.*;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.entity.OrganizationEntity;
import com.daoshu.system.entity.OrganizationPersonEntity;
import com.daoshu.system.entity.PersonEntity;
import com.daoshu.system.service.OrgFeignService;
import com.daoshu.system.service.PersonFeignService;
import com.daoshu.system.service.PersonOrgFeignService;
import com.daoshu.system.utils.RequestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  微群服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Service
public class MicroGroupServiceImpl extends ServiceImpl<MicroGroupMapper, MicroGroupEntity> implements IMicroGroupService {

	@Autowired private RequestUtils userUtil;
	@Autowired @Lazy private IMicroGroupMemberService microGroupMemberService;
	@Autowired private IMicroGroupMessageService microGroupMessageService;
	@Autowired private MicroGroupMapper microGroupMapper;
	@Autowired private MicroGroupMemberMapper microGroupMemberMapper;
	@Autowired private PersonFeignService personService;
	@Autowired private PersonOrgFeignService organizationPersonService;
	@Autowired private OrgFeignService organizationService;
	@Autowired @Lazy private IMessageService messageService;

	@Autowired
	private IMicroGroupBusinessService microGroupBusinessService;
	
	@Override
	public MicroGroupEntity addMicroGroup(MicroGroupBO bo) {
		if(!MicroGroupType.SINGLE_GROUP.getStatus().equals(bo.getGroupType())) {
			return addGroupGroup(bo);
		}else { 
			return addSingleGroup(bo);
		}
	}
	/**
	 * 多人聊天
	 *
	 * @param bo
	 * @return
	 */
    private MicroGroupEntity addGroupGroup(MicroGroupBO bo) {
		AccountBo user = userUtil.getCurrentUser();

        MicroGroupEntity group = new MicroGroupEntity();
        BeanUtils.copyProperties(bo, group);
        group.setCreatorId(user.getPersonBo().getId());
        group.setCreatorName(user.getPersonBo().getName());
        group.setCreateTime(new Date());
        group.setGroupType(bo.getGroupType());
        group.setDelete(0);
		group.setLastMessageUpdateTime(new Date());
        this.save(group);

		//关联业务
		if (bo.isBusiness()) {
			MicroGroupBusiness microGroupBusiness = bo.getMicroGroupBusiness();
			if (null != microGroupBusiness) {
				microGroupBusiness.setMicroGroupId(group.getId());
				microGroupBusiness.setCreateId(user.getPersonBo().getId());
				microGroupBusiness.setCreateTime(new Date());
				microGroupBusinessService.save(microGroupBusiness);
			}
		}

        List<MicroGroupMemberEntity> members = initMembers(group.getId(), bo.getMembers());
		MicroGroupMessageEntity entity = new MicroGroupMessageEntity();
        StringBuffer sb = new StringBuffer(group.getCreatorName())
                .append(" ")
                .append("邀请 ");
        for(int i = 0; i < members.size(); i++) {
        	if(i <= 5) {
        		MicroGroupMemberEntity item = members.get(i);
        		if (!group.getCreatorName().equals(item.getPersonName())) {
            		if(StringUtils.isNoneBlank(item.getPersonName())){
						sb.append(item.getPersonName()).append(",");
					}
    			}
        	}else {
        		sb.setLength(sb.length() - 1);
        		sb.append(" 等").append(members.size()).append("人,");
        		break;
        	}
        }
        /*members.forEach(item -> {
        	if (!group.getCreatorName().equals(item.getPersonName())) {
        		if(StringUtils.isNoneBlank(item.getPersonName()))
        			sb.append(item.getPersonName()).append(" ");
			}
		});*/
//        if(StringUtils.isBlank(group.getTitle())) {
//            for(MicroGroupMemberEntity m:members) {
//                if(m.getPersonId()!=null&&!m.getPersonId().equals(user.getPersonId())) {
//                    group.setTitle(m.getPersonName());
//                    sb.append(m.getPersonName());
//                }
//            }
//        }
        microGroupMemberService.saveBatch(members);
        sb.setLength(sb.length() - 1);
        sb.append(" 加入群聊");
        entity.setContent(sb.toString());
        entity.setCreateName("系统消息");
        entity.setMicroGroupId(group.getId());
        entity.setCreateId(user.getPersonBo().getId());
        entity.setType(MessageType.SYSTEM_INFO.getType());
		entity.setMicroGroupName(bo.getTitle());
        entity.setCreateTime(new Date());
        messageService.sendMessage(entity);
        return group;
    }
	/**
	 * 单对单聊天
	 * @param bo
	 */
	private MicroGroupEntity addSingleGroup(MicroGroupBO bo) {
		AccountBo user = userUtil.getCurrentUser();
		List<MicroGroupMemberEntity> result = new ArrayList<>();
		String member = "";
		if(bo.getMembers()!=null&&bo.getMembers().size()>1) {
			result = microGroupMemberMapper.querySingleMember(bo.getMembers().get(0), bo.getMembers().get(1));
			if(bo.getMembers().get(0).equals(user.getPersonId())) {
				member = bo.getMembers().get(1);
			}else {
				member = bo.getMembers().get(0);
			}
			
		}else if(bo.getMembers()!=null&&bo.getMembers().size()==1) {
			member = bo.getMembers().get(0);
			result = microGroupMemberMapper.querySingleMember(bo.getMembers().get(0), user.getPersonId());
		}
		if(null!=result&&!result.isEmpty()) {
			MicroGroupEntity entity = this.getById(result.get(0).getMicroGroupId());
			if(!user.getPersonId().equals(entity.getCreatorId())) {
				entity.setTitle(entity.getCreatorName());
			}
			return entity;
		}else {
			List<String> members = new ArrayList<>();
			members.add(member);
			Collection<PersonEntity> persons = personService.listByIds(members);
			if(CollectionUtils.isNotEmpty(persons)){
				bo.setTitle(persons.iterator().next().getName());
			}
			return addGroupGroup(bo);
		}
	}
	private List<MicroGroupMemberEntity> initMembers(String groupId,List<String> membersTemp){
		if(CollectionUtils.isEmpty(membersTemp)) {
			throw new BusinessException(500, "请选择微群成员");
		}
		List<String> members = new ArrayList<>(membersTemp.size());
		for(String member:membersTemp) {
			if(!members.contains(member)){
				members.add(member);
			}
		}
		AccountBo user = userUtil.getCurrentUser();
		List<MicroGroupMemberEntity> memberEntity = new ArrayList<>(members.size());
		Date date = new Date();
		/*PersonConcatsQO qo = new PersonConcatsQO();
		qo.setPersonIds(members);
		qo.setSize(members.size());*/
		Collection<PersonEntity> persons = personService.listByIds(members);
		// IPage<ContentBO> page = personService.queryPersonPage(qo);
		// List<ContentBO> persons = Optional.ofNullable(page.getRecords()).orElse(new ArrayList<>());
		members.forEach(a->{
			MicroGroupMemberEntity m = new MicroGroupMemberEntity();
			persons.forEach(person->{
				if(person.getId()!=null&&person.getId().equals(a)) {
					OrganizationPersonEntity org = organizationPersonService.getOne(person.getId());
					m.setPersonName(person.getName());
					if(null != org) {
						m.setPersonOrgId(org.getOrgId());
						m.setPositionName(org.getPositionName());
					}
					m.setPersonOrgName(Optional.ofNullable(organizationService.getById(org.getOrgId())).orElse(new  OrganizationEntity()).getName());
					m.setPersonType(1);
					m.setMainDuty(person.getMainDuty());
				}
			});
			m.setCreateTime(date);
			m.setCreatorId(user.getPersonBo().getId());
			m.setPersonId(a);
			m.setReadedTime(date);
			m.setReadImportTime(date);
			m.setMicroGroupId(groupId);
			m.setDelete(0);
			memberEntity.add(m);
		});
//		if(!members.contains(user.getPersonId()))
//			members.add(user.getPersonId());
		return memberEntity;
	}

	@Override
	public IPage<MicroGroupBO> queryMicroGroupInPerson(MicroGroupQO qo) {
		AccountBo user = userUtil.getCurrentUser();
		QueryWrapper<MicroGroupMemberEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("person_id_", user.getPersonBo().getId());
		List<MicroGroupMemberEntity> members = microGroupMemberService.list(queryWrapper);
		Map<String, Date> readTimes = new HashMap<String, Date>();
		if(members!=null && !members.isEmpty()) {
			List<String> groupIds = new ArrayList<>();
			members.forEach(a->{
				groupIds.add(a.getMicroGroupId());
				readTimes.put(a.getMicroGroupId(), a.getReadedTime());
			});
			QueryWrapper<MicroGroupEntity> query = new QueryWrapper<MicroGroupEntity>();
			if (StringUtils.isNotBlank(qo.getTitle())) {
				query.like(true, "title_", qo.getTitle());
			}

			query.orderByDesc("last_message_update_time");
			query.orderByDesc("create_time_");
			query.in("id_", groupIds);
			IPage<MicroGroupEntity> page = this.page(new Page<MicroGroupEntity>(qo.getStart(), qo.getSize()), query);

			// 查询微群业务关联列表
			List<MicroGroupBusiness> microGroupBusinessList = microGroupBusinessService.list(new QueryWrapper<>());

			List<MicroGroupEntity> list = Optional.ofNullable(page.getRecords()).orElse(new ArrayList<>());
			List<MicroGroupBO> result = new ArrayList<>();
			list.forEach(entity->{
				MicroGroupBO bo = new MicroGroupBO();
				BeanUtils.copyProperties(entity, bo);
				bo.setUnReadCount(microGroupMessageService.count(new QueryWrapper<MicroGroupMessageEntity>().eq("micro_group_id_", bo.getId()).ge("create_time_", readTimes.get(bo.getId()))));
				bo.setLatestMessage(microGroupMessageService.getOne(new QueryWrapper<MicroGroupMessageEntity>().eq("micro_group_id_", bo.getId()).orderByDesc("create_time_")));
				if(MicroGroupType.SINGLE_GROUP.getStatus().equals(entity.getGroupType())) { // 这是单聊,显示的微群名称为对方姓名
					/*MicroGroupMemberEntity member = microGroupMemberService.getOne(new QueryWrapper<MicroGroupMemberEntity>().lambda()
							.eq(MicroGroupMemberEntity::getMicroGroupId, entity.getId())
							.ne(MicroGroupMemberEntity::getPersonId, user.getPersonId()));
					if(member!=null)*/
					if(entity.getCreatorId()!=null&&entity.getCreatorId().equals(user.getPersonId())) {
						bo.setTitle(entity.getTitle());
					}else {
						bo.setTitle(entity.getCreatorName());
					}
				}

				// 微群关联业务数据
                microGroupBusinessList.forEach(microGroupBusiness -> {
                    if (bo.getId().equals(microGroupBusiness.getMicroGroupId())) {
                        bo.setMicroGroupBusiness(microGroupBusiness);
                        bo.setBusiness(true);
                    }
                });
				result.add(bo);
			});
			IPage<MicroGroupBO> resultPage = new Page<MicroGroupBO>();
			resultPage.setTotal(page.getTotal());
			return resultPage.setRecords(result);
		}
		return new Page<MicroGroupBO>();
	}

	@Override
	public void deleteMicroGroup(String groupId) {
		if(StringUtils.isBlank(groupId)) {
			throw new BusinessException(500, "微群ID不能为空");
		}
		Optional.ofNullable(this.getById(groupId)).orElseThrow(()->{
			return new BusinessException(500, "没有此微群");
		});
		this.removeById(groupId);
		microGroupMemberService.remove(new QueryWrapper<MicroGroupMemberEntity>().eq("micro_group_id_", groupId));
		microGroupMessageService.remove(new QueryWrapper<MicroGroupMessageEntity>().eq("micro_group_id_", groupId));
	}

	@Override
	public List<Map<String, String>> getAllMGToMember() {
		return microGroupMapper.getAllMGToMembers();
	}

	@Override
	public Integer getUnreadCount(String personId) {
		return microGroupMapper.getUnreadCount(personId);
	}
}
